/**
 * Created by Administrator on 2017/10/20.
 */
import React from 'react';
import css from './index.less';
import reqwest from 'reqwest';
// import Data from 'data';
import Data from '../home/datas';
import Back from 'components/back';
import TopBar from 'components/topBar';
import { observer, inject } from 'mobx-react';
import { Icon } from 'antd';
import chunk from 'lodash/chunk';
import ImgText from 'assets/img/text.png';
import ImgStar from 'assets/img/star.png';
import Imgleft from 'assets/img/left.png';
import ImgRight from 'assets/img/right.png';

// import ImgPoc from 'assets/img/poc.png';
// import ImgNone from 'assets/img/resError.png';
// import ImgGoods from 'assets/img/goods.png';
// import ImgGet from 'assets/img/get.png';
// import ImgResult from 'assets/img/result.png';
const ImgPoc = 'https://img.alicdn.com/imgextra/i2/3355153118/TB2.fkAXBLN8KJjSZFPXXXoLXXa-3355153118.png';
// 小的图片
// const ImgNone = 'https://img.alicdn.com/imgextra/i2/3355153118/TB2aG_5X3vD8KJjSsplXXaIEFXa-3355153118.png';
// const ImgGoods = 'https://img.alicdn.com/imgextra/i2/3355153118/TB2O2Y9X2DH8KJjy1XcXXcpdXXa-3355153118.png';
// const ImgGet = 'https://img.alicdn.com/imgextra/i2/3355153118/TB2qXobXZnI8KJjSsziXXb8QpXa-3355153118.png';
// const ImgResult = 'https://img.alicdn.com/imgextra/i1/3355153118/TB2ozsEXxk98KJjSZFoXXXS6pXa-3355153118.png';

const ImgError = 'https://img.alicdn.com/imgextra/i4/3355153118/TB20cixaf6H8KJjSspmXXb2WXXa-3355153118.png';
const ImgNone = 'https://img.alicdn.com/imgextra/i3/3355153118/TB2UFuzaCfD8KJjSszhXXbIJFXa-3355153118.png';
const ImgGoods = 'https://img.alicdn.com/imgextra/i1/3355153118/TB2pkqsacjI8KJjSsppXXXbyVXa-3355153118.png';
const ImgGet = 'https://img.alicdn.com/imgextra/i1/3355153118/TB2CPeyagvD8KJjy0FlXXagBFXa-3355153118.png';
const ImgResult = 'https://img.alicdn.com/imgextra/i4/3355153118/TB2ZXiratrJ8KJjSspaXXXuKpXa-3355153118.png';


@inject('store')
@observer
export default class Inner extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      palace: Data[props.match.params.palaceId],
      swiper: {},
      goodList: [],
      showRes: false,
      myName: '',
      remark: '',
      isWin: null,
    };
  }

  notEndTime() {
    const {h, m, s } = this.props.store;
    // this.props.store.openPocket();
    // console.log('pocket', this.props.store.pocket);
    return (
      <div className={css.times}>
        <img src={ImgText} className={css.imgText}/>
        <div className={css.time}>
          <span>0:</span>
          <span>{m}:</span>
          <span>{s}</span>
        </div>
        <img src={ImgPoc} className={css.timeImg}/>

      </div>
    );
  }

  // check() {
  //   // 收藏商品
  //   Tida.itemFavor({
  //     action: 'add',
  //
  //     itemId: '559964345943'// 商品ID 注意这里只能用string
  //   }, function(data) {
  //     // console.log(data);
  //   });
  // }

  isEndTime() {
    return (
      <div className={css.times}>
        <p>可以抢红包啦！</p>
        <img src={ImgPoc} className={css.timeImg} onClick={() => {
          this.openPoket();
        }} />
      </div>
    );

  }
  sendCoupon() {
    const { coupon, integer } = this.props.store;
    const isWin = Math.random();
    if (isWin < 0.7) {
      this.setState({
        isWin: true,
      });
      let amount = 0;
      coupon.forEach( (item, index) => {
        if (integer && item.c_getTimeType === 2 ) {
          amount += item.c_amount * 2;
        } else {
          amount += item.c_amount;
        }
      });

      const number = Math.random() * amount;
      let ind = 0;
      let addNum = 0;
      for (let i = 0; i < coupon.length; i++) {
        if (integer === true && coupon[i].c_getTimeType === 2 ) {
          if (number < addNum + 2 * coupon[i].c_amount) {
            ind = i;
            break;
          } else {
            addNum += 2 * coupon[i].c_amount;
          }
        } else {
          if (number < addNum + coupon[i].c_amount) {
            ind = i;
            break;
          } else {
            addNum += coupon[i].c_amount;
          }
        }
      }
      const myUrl = coupon[ind].c_url;
      const myName = coupon[ind].c_name;
      // let remark = coupon[ind].c_remark;
      const remark = coupon[ind].c_remark.split('-');
      // console.log('myName', myName);
      // console.log('myName', remark);
      this.setState({
        myName: myName,
        remark: remark[0],
      });
      const urlArr = myUrl.split('?');
      const url = '//taoquan.taobao.com/coupon/unify_apply.htm?' + urlArr[1];

      // const url = '//taoquan.taobao.com/coupon/unify_apply.htm?sellerId=3355153118&activityId=28996fc8bed141b48ae5c540ad6d9069';
      // console.log('url', url);
      const that = this;
      window.TB = {
        Act: {
          callback: (data) => {
            console.log('Act adta', data); // 领取成功就可以执行
            that.setState({
              showRes: data.success,
            });
            // that.props.store.setRes(data.success);
          }
        }
      };
      // console.log('window.TB', window.TB);
      reqwest({
        url: url + '&json=true',
        type: 'jsonp',
        jsonpCallback: 'callback',
        jsonpCallbackName: 'callback',
        success: (data) => {
          console.log('reqwest adta', data);
        },
        error: (err) => {
          console.log('err', err);
        },
      });
    } else {
      this.setState({
        isWin: false,
      });
    }

  }

  // showQuan(data) {
  //   console.log('data===', data);
  //
  // }

  openPoket() {

    // 点击默认关注店铺
    reqwest({
      url: '//showcase.display.taobao.com/store/addStore.json',
      data: {'app': 'vansShop', 'storeId': '157260118'},
      type: 'jsonp',
      jsonpCallback: 'callback',
      jsonpCallbackName: 'callback',
      success: (data) => {
        // console.log(data);
      }
    });

    this.sendCoupon();

    this.props.store.openPocket(true);
  }

  renderOpen() {

    const { myName, remark, showRes } = this.state;
    // const { showRes } = this.props.store;
    // console.log('pocket', this.props.store.pocket);
    const errProps = {
      className: css.result,
      onClick: this.close.bind(this),
    };
    const sussProps = {
      className: css.getPoc,
      onClick: this.close.bind(this),
    };

    if (showRes === 'false') {
      return (
        <div {...errProps}>
          <img src={ImgError} onClick={() => {
            window.location.href = 'https://palacemuseum.m.tmall.com/?shop_id=157260118';
          }}/>
        </div>
      );
    } else if (showRes === 'true') {
      if (this.state.isWin) {
        return (
          <div {...sussProps}>
            <img src={ImgGet} />
            <div>
              <p>恭喜您抢到</p>
              <p>{myName}</p>
              <p>满{remark}使用</p>
              <p>已存入您的卡券中</p>
              <img src={ImgPoc} className={css.img}/>
              <p>仅限11.11使用</p>
            </div>
          </div>);
      } else {
        return (
          <div {...errProps}>
            <img src={ImgNone} />
          </div>
        );
      }
      return null;
    }
  }
  close() {
    this.props.store.openPocket(false);
  }

  // palaceData() {
  //   // console.log(111);
  //   // const { palaceList } = this.props.store;
  //   // // const { palaceList2} = palaceList[0];
  //   //
  //   // console.log('this.props.store', palaceList);
  //   // // console.log('palaceList2', palaceList2);
  //   //
  //   // // console.log('this.props.store', palaceList[0]);
  //   // // const { p_peopleEnd } = palaceList[0][0];
  //   // // setTimeout(() => {
  //   // //   console.log( 'palaceList', palaceList[0]);
  //   // // }, 0);
  //   // // console.log( 'palaceList', palaceList[0][0].p_peopleEnd);
  //   // // console.log( 'palaceList', p_peopleEnd);
  //   // return (
  //   //   <div>我在这里
  //   //      {/*{ p_peopleEnd }*/}
  //   //
  //   //   </div>
  //   // );
  //   // clearInterval(this.time);
  //   const { palace } = this.state;
  //   const { palaceId } = this.props.match.params;
  //   // console.log(palaceId); // 对应的数字编号
  //
  //   const { test } = this.props.store;
  //   let star;
  //   let p_start;
  //   let p_end;
  //   if (test[palaceId]) {
  //     // console.log(test[1].id);
  //     star = test[palaceId].star;
  //     p_start = test[palaceId].p_start;
  //     p_end = test[palaceId].p_end;
  //   }
  //
  //   let people = Math.round(Math.random() * (p_end - p_start) + p_start);
  //
  //   return (
  //   <div className={css.people}>
  //     <div>
  //       { palace.label } 当前人数： { people }
  //     </div>
  //     <div>
  //       拥挤指数： { star }
  //     </div>
  //   </div>
  //
  //   );
  //
  // }

  showStar() {
    const { star } = this.props.store;
    switch (star) {
      case 2 : return (<div className={css.star}>拥挤指数&nbsp;&nbsp;&nbsp;<img src={ImgStar} /><img src={ImgStar} /></div>); break;
      case 3 : return (<div className={css.star}>拥挤指数&nbsp;&nbsp;&nbsp;<img src={ImgStar} /><img src={ImgStar} /><img src={ImgStar} /></div>); break;
      case 4 : return (<div className={css.star}>拥挤指数&nbsp;&nbsp;&nbsp;<img src={ImgStar} /><img src={ImgStar} /><img src={ImgStar} /><img src={ImgStar} /></div>); break;
      case 5 : return (<div className={css.star}>拥挤指数&nbsp;&nbsp;&nbsp;<img src={ImgStar} /><img src={ImgStar} /><img src={ImgStar} /><img src={ImgStar} /><img src={ImgStar} /></div>); break;
    }
  }

  // goodsList = () => {
  //   let { good } = this.props.store;
  //   good.map( (items, index) => {
  //     // console.log(items);
  //     let props = {
  //       goods: items,
  //       key: index,
  //     };
  //     return <Goods {...props}/>;
  //
  //   });
  // };

  tiaozhuan(id) {

    // console.log(id);
    // console.log(123123123);
    window.location.href = `//detail.m.tmall.com/item.htm?spm=a220m.6910245.0.0.437533ed2A7LZI&id=${id}&skuId=3434459743980&pic=//img.alicdn.com/bao/uploaded/i4/2893966855/TB29UIiqYXlpuFjy1zbXXb_qpXa_!!2893966855.jpg_620x10000Q50s50.jpg_.webp&itemTitle=abcprice=49.00&from=h5`;

  }

  renderItem(item, index) {

    const subStr = (str, length) => {return str.length>length ? `${str.substr(0, length)}...` : str;};
    return (
      item.map( (item, index) => {
        item.g_title = item.g_title.replace('故宫博物院官方旗舰店', '');
        item.g_title = item.g_title.replace('双11预售', '');
        item.g_title = subStr(item.g_title, 14);
        return (
          <div key={index} className={css.single} >
            <img src={item.g_imgUrl} onClick={ () => {
              this.tiaozhuan(item.g_num);
            } }/>
            <p className={css.price}>￥{item.g_price}</p>
            <p className={css.title}>{item.g_title}</p>

          </div>
        );
      })
    );

  }

  renderGoods() {
    const { pal } = this.props.store;
    this.goodList = pal[this.props.match.params.palaceId].p_goodsList;
    // console.log(this.goodList);
    let good = chunk(this.goodList, 3);
    return (
      good.map((item, index) => {
        // console.log('item', item);
        return (
          <div className={'swiper-slide'} key={index}>
            {this.renderItem(item, index)}
          </div>
        );
      })
    );

  }

  leftButton() {
    this.swiper.slidePrev();
  }

  rightButton() {
    this.swiper.slideNext();
  }

  quesClick() {
    this.props.store.quesSet(true);
  }
  ques() {
    const {quesClick} = this.props.store;
    const props = {
      className: css.ques,
      onClick: () => {
        this.props.store.quesSet(false);
      }
    };
    if (quesClick) {
      return (
        <div className={css.quesBox}>
          <img src={ImgResult} {...props}/>
        </div>
      );
    }
  }


  componentDidMount() {

    const { start, end } = this.props.store;
    let people = Math.round(Math.random() * (end - start) + start );
    this.props.store.peopleChange(parseInt(people));

    // loop 会复制一层，但是事件没有克隆，所以会影响点击事件
    this.swiper = new Swiper('.swiper-container', {
      autoplayDisableOnInteraction: false,
      autoplay: 5000,
      speed: 400,
      // loop: true
    });

  }


  render() {

    const { palace } = this.state;
    const { endTime, people, pocket, musicPlay } = this.props.store;

    const props = {
      className: css.palaceDetail,
      style: {
        backgroundImage: `url(${palace.bg})`,
      }
    };

    const topProps = {
      quesClick: this.quesClick.bind(this),
      isMusic: musicPlay,
    };
    return (

      <div {...props}>
        <div className={css.meng}></div>
        <Back history={this.props.history}/>
        <TopBar {...topProps}/>
        {this.ques()}

        <div className={css.packet}>
          {
            endTime ? this.isEndTime() : this.notEndTime()
          }
        </div>

        { pocket && this.renderOpen()}

        <div className={css.people}>
          <div>
            { palace.label }当前人数 &nbsp;&nbsp;{ people } &nbsp;人
          </div>
          { this.showStar() }
        </div>


        <div className={css.pageBottom}>
          <img src={ImgGoods} className={css.ImgGoods} />
          <img src={Imgleft} onClick={() => { this.leftButton(); }} className={css.leftButton}/>
          <img src={ImgRight} onClick={() => { this.rightButton(); }} className={css.rightButton}/>
          <div className={'swiper-container'}>
            <div className={'swiper-wrapper'}>
              {this.renderGoods()}
            </div>
          </div>
        </div>

      </div>
    );
  }
}

